import { Injectable } from "@angular/core";
import {Platform, AlertController, LoadingController} from 'ionic-angular';
import {FileService} from "../native/file/file.service";
import {ToastService} from "./toast.service";
import {FileOpener} from "@ionic-native/file-opener";
import {AppVersion} from "@ionic-native/app-version";
import {HttpClient} from "@angular/common/http";
import { InAppBrowser } from '@ionic-native/in-app-browser';
import {Observable} from "rxjs/Observable";

@Injectable()
export class VersionService {
    private modal: HTMLElement;
    private version: any;

    constructor(private alertCtrl:AlertController,
                private loadingCtrl:LoadingController,
                private fileService:FileService,
                private toastService:ToastService,
                private opener:FileOpener,
                private http: HttpClient,
                private appversion:AppVersion,
                private iab: InAppBrowser) {
        this.modal = null;
    }

    public init(element: HTMLElement) {
        if (typeof element === "undefined" || element == null) {
            return;
        }
        this.modal = element;
        this.modal.hidden = true;
    }
    public show() {
        if (this.modal == null) {
            return;
        }
        this.modal.hidden = false;
    }
    public hide() {
        if (this.modal == null) {
            return;
        }
        this.modal.hidden = true;
    }
    //检查版本
    public checkVersion(platform:string){
        return this.appversion.getVersionNumber().then(currentVersion=>{
            return this.getNewestVersion(currentVersion,platform);
        }).catch(c=>{
            throw c.toString();
        });
    }
    //更新app
    public updateApp(fileAddress){
        // this.fileService.getFilePath(fileName).subscribe(res=>{
        //     this.viewAttachFile(res.sasUrl,fileName);
        // });
        let fileName = 'Agency-Mobile.apk';
        if(fileAddress.indexOf('.apk')>-1){
            let temp = fileAddress.substring(0,fileAddress.indexOf('.apk'));
            fileName = temp.substring(temp.lastIndexOf('/')+1)+".apk";
        }
        this.viewAttachFile(fileAddress,fileName);
    }
    //ios 上更新app
    public installToIOS(url){
        this.iab.create(url,'_system');
    }
    //获取最新的版本
    getNewestVersion(currentVersion,platform):Observable<any>{
        return this.http.get("/version/v1/appVersion?version="+currentVersion+"&platform="+platform);
    }
    viewAttachFile(resourceId: string,fileName:string) {
        let now = 0;
        console.log(resourceId);
        if (resourceId) {
            let loading = this.loadingCtrl.create({
                spinner: 'circles',
                content: '文件下载中: 0%',
                dismissOnPageChange: false,
                enableBackdropDismiss: false
            });
            loading.onDidDismiss(() => {
                // console.log('on did dissmisse');
                this.fileService.abort();
            });
            loading.present();

            this.fileService.onProgress(progressEvent => {
                if (progressEvent.lengthComputable) {
                    now = progressEvent.loaded / progressEvent.total * 100;
                }
            });

            let mTimer = setInterval(() => {
                loading.setContent('文件下载中: ' + Math.floor(now) + '%');
                if (now == 100) {
                    clearInterval(mTimer);
                }
            }, 300);
            this.fileService.downloadFileAndInstall(resourceId,fileName).then(res=>{
                loading.dismiss();
                this.opener.open(res.toString(), 'application/vnd.android.package-archive').then(openRes=>{
                    console.log("install result"+openRes);
                }).catch(error=>{
                    console.log("file open error "+error);
                });
            },error2 => {
                loading.dismiss();
            })

        } else {
            this.toastService.showToast('文件异常！');
        }

    }
}
